<?php

declare(strict_types=1);

namespace App\Robot\Job;

use App\CustHub\Constants\CrowSendingConstants;
use App\CustHub\Model\ChCrowdInvite;
use App\CustHub\Service\ChSendRecordService;
use App\CustHub\Service\CrowdInviteService;
use Carbon\Carbon;
use Hyperf\AsyncQueue\Job;
use Psr\Log\LoggerInterface;
use function Hyperf\Collection\data_get;
use function Hyperf\Coroutine\co;

class CrowdInviteJob extends Job
{
    public array $data;

    /**
     * 任务执行失败后的重试次数，即最大执行次数为 $maxAttempts+1 次
     */
    protected int $maxAttempts = 2;

    public function __construct(array $data)
    {
        $this->data = $data;
    }

    public function handle()
    {
        $logger = container()->get(LoggerInterface::class);
        $logger->info("群邀请延迟任务处理中...",[
            'time' => Carbon::now()->toDateTimeString()
        ]);
        try {
            $schemeId = $this->data['schemeId'];
            $subSchemeId = $this->data['subSchemeId'];
            $robotId = $this->data['robotId'];
            $customId = $this->data['customId'];
            $isLastCustom = $this->data['isLastCustom'];
            $crowdInvite = ChCrowdInvite::query() -> where('id',$schemeId) -> first();
            if(empty($crowdInvite)){
                return false;
            }
            $roomCnf = $crowdInvite->crowd_conf;
            $roomCnf['invite_guide_switch'] = $crowdInvite->is_guide;
            $roomCnf['guide_text'] = $crowdInvite->content;
            if(!empty($crowdInvite) && $crowdInvite-> status == CrowSendingConstants::SENDING){
                container()->get(CrowdInviteService::class)->triggerInvite($schemeId, $robotId, $customId, $roomCnf,$subSchemeId,$isLastCustom);
            }

            $logger->info("Task CrowdInviteJob successfully", ['data' => $this->data]);

        } catch (\Exception $e) {
            $logger->error("Task CrowdInviteJob failed", [
                'data' => $this->data,
                'error' => $e->getMessage(),
            ]);

            throw $e;
        }
    }

    public function failed(array $data, \Throwable $exception)
    {
        $logger = container()->get(LoggerInterface::class);
        $logger->critical("Task failed after max retries", [
            'data' => $data,
            'error' => $exception->getMessage(),
        ]);

        $this->sendAlert($data);
    }

    protected function sendAlert(array $data)
    {
        echo "Alert: Task has failed after maximum retries.\n";
    }
}